(function () {
	etlinking.views.friendList = new FriendListFunc();

	function FriendListFunc () {
		var _self = this;

		_self.init = init;

		var socialActions = nsbase.config.actionUrl.social,
			utilities = nsbase.utility,
			validations = nsbase.utility.validations,
        	clientResource = nsbase.resources.clientResource;

		var cssClass = {
			selected:"selected"
		};
		function init(){
      		$(".nav_menu li.Social").addClass(cssClass.selected);
      		bindFriedGrid();
			//initFriendWall($friendWall);
			bindHandler();
		}

		var $txtSearch = $("#txtSearch"),
			$btnSearch = $("#btnSearch"),
			$friendWall = $(".friend_wall"),
			$gridContainer = $("#friendContainer"),
			$friendWallItemTmpl;

		var userId = parseInt($("#txtUserId").val());
		function bindHandler(){
			$txtSearch.focus(function(){
				var sender = $(this);
				var defaultValue = sender.attr("default-value");
				var value = sender.val();
				if(value == defaultValue){
					sender.val("");
				}
			}).blur(function(){
				var sender = $(this);
				var defaultValue = sender.attr("default-value");
				var value = utilities.trim(sender.val());
				if(!value){
					sender.val(defaultValue);
				}
			});

			$btnSearch.click(function(){
				var searchValue = utilities.trim($txtSearch.val());
				var defaultValue = $txtSearch.attr("default-value");
				if(!searchValue || searchValue == defaultValue){
					utilities.errorDialog(clientResource.msgSearchFriend);
					return;
				}

				bindFriedGrid(searchValue);

				/*
				var pageConfig = {
	                container: $friendWall,
	                remote:true,
	                actionUrl:socialActions.searchFriend,
	                actionParams:{
	                	user_name:searchValue
	                },
	                pageSize:10,
	                pageHandler:function (results){ 
	                    bindFriendWall($friendWall,results,"order");
	                }
	            }
				var pageBar = new nsbase.controls.pageBar(pageConfig);
				*/
			});
		}


		var rowCount = 4,
			columnCount = 6;
		function initFriendWall (container) {
			var $wallObj = container.find("ul");
			$friendWallItemTmpl = $wallObj.find("li:first").clone();
			for (var row = 0; row < rowCount; row++) {
				for (var column = 0;  column < columnCount; column++) {
					var $itemObj = $("<li></li>");
					if((row + column)%2 == 0){
						$itemObj.addClass("odd");
					} else {
						$itemObj.addClass("even");
					}
					$wallObj.append($itemObj);
				};
			};

            var pageConfig = {
                container: container,
                remote:true,
                actionUrl:socialActions.getFriendList,
                actionParams:{},
                pageSize:10,
                pageHandler:function (results){ 
                    bindFriendWall(container,results,"random");
                }
            }
			var pageBar = new nsbase.controls.pageBar(pageConfig);
		}

		function bindFriendWall(friendWallContainer,results,renderType){
            friendWallContainer.find("li").empty();
            if(renderType == "random"){
				var randomArray = getRandomArray();
			}
			$.each(results,function(index,friendInfo){
				var $friendItemContainer = friendWallContainer.find("li").eq(index+1);
				if(renderType == "random"){
					var sliceIndex = parseInt(Math.random()*randomArray.length);
					$friendItemContainer = friendWallContainer.find("li").eq(randomArray.splice(sliceIndex,1));
				}
				var $friendItem =$(utilities.tmplFormat($friendWallItemTmpl.html(),friendInfo,friendFormat));
				var $friendPhoto = $friendItem.find("img[src-path]");
				$friendPhoto.attr("src",$friendPhoto.attr("src-path"));
				$friendPhoto.removeAttr("src-path");
				$friendItem.find(".flag").click(friendManage);
				$friendItemContainer.append($friendItem);
			});

			// friendWallContainer.find(".wall_item").hover(function(){
			// 	var sender = $(this);
			// 	var descDiv = sender.find(".desc");
			// 	descDiv.css({marginTop: -descDiv.height()});
			// 	// descDiv.animate({marginTop: -descDiv.height()});
			// },function(){
			// 	var sender = $(this);
			// 	var descDiv = sender.find(".desc");
			// 	descDiv.css({marginTop:0});
			// });
		}
		function friendFormat (friendInfo,dataIndex) {
			if(dataIndex == "photo"){
				var value = friendInfo[dataIndex];
				if(!value){
					return "../static/images/photo.png";
				}

				return value;
			}

			if(dataIndex == "relationship"){
				var relationEnum = nsbase.enums.relationshipEnum.getEnumByValue(friendInfo[dataIndex]);
				return relationEnum.key;
			}
		}
		function getRandomArray () {
			var normalArray =[];
			for (var i = 1; i <= rowCount * columnCount; i++) {
				normalArray.push(i);
			};
		 	return normalArray.sort(function(){ return Math.random()>0.5?-1:1;});
		}

		function friendManage () {
			var sender = $(this);
			var $container = sender.parent(".wall_item:first");
			var cls = {
				strange:"strange",
				friend:"friend"
			};
			var action = socialActions.addFriend;
			if(sender.hasClass(cls.strange)){
				action = socialActions.addFriend;
			} else if(sender.hasClass(cls.friend)){
				action = socialActions.delFriend;
				if(!confirm(clientResource.msgDelFriendConfirm)){
					return;
				}
			}
			$container.mask();
			var param = {
				user_id: $container.attr("user-id")
			}
			nsbase.ajax.request(action,param,function(result){
				$container.unmask();
				if(result.success){
					if(sender.hasClass(cls.strange)){
						alert(clientResource.msgWaitForConfirm);
					} else if(sender.hasClass(cls.friend)){
						sender.removeClass(cls.friend).addClass(cls.strange);
					}
				}
			},function () {
				$container.unmask();
			});
		}


		function bindFriedGrid (userName) {
			var gridConfig = {
				renderTo:"friendContainer",
				height:500,
				rowNumber:true,
				columns:[
					//{title:"",dataIndex:"ranking",width:30,formater:rankingFormatter},
					{title:"",dataIndex:"photo",width:40,formater:photoFormatter},
					{title:clientResource.columnFriendName,dataIndex:"user_name",width:200},
					{title:clientResource.columnFriendCalorie,dataIndex:"calorie",width:145,align:"left",sortable:true,selectable:true,formater:colorieFormatter},
					{title:clientResource.columnFriendMiles,dataIndex:"miles",width:150,sortable:true,selectable:true},
					{title:clientResource.columnFriendSteps,dataIndex:"steps",width:150,sortable:true,selectable:true},
					{title:clientResource.columnFriendSleep,dataIndex:"sleeptime",width:150,sortable:true,selectable:true},
					{title:clientResource.columnFriendOperation,dataIndex:"relationship",width:100,formater:manageFormater}
				],
				rowSelectable:"none",
				paggingBar: {
					remote: true,
					pageIndex: 1,
					pageSize: 8
				},
				store:{
					data: {
						searchName:userName?userName:"",
						sortField:"calorie",
						sortDirect:"DESC"
					}, 
					url: socialActions.searchUsers,
				}
			}
			var gridEvents = nsbase.controls.grid.setting.eventEnums;
			var friendGrid = new nsbase.controls.grid(gridConfig);
			friendGrid.on(gridEvents.rowClick,function(sender,rowData){
				location.href = socialActions.friendDetail + "?friendId=" + rowData.user_id;
			});
			friendGrid.on(gridEvents.columnSelectChanged,function(columnEl,rowData){
				
			});
			friendGrid.on(gridEvents.cellClick,function(event,rowData){
				var sender = $(event.target);
				var action = "";
				if(sender.is(".add")){
					event.stopPropagation();
					action = socialActions.addFriend;
				} else if(sender.is(".del")) {
					event.stopPropagation();
					action = socialActions.delFriend;
					if(!confirm(clientResource.msgDelFriendConfirm)){
						return;
					}
				}

				var param = {
					friendId: rowData.user_id
				};
				$gridContainer.mask();
				nsbase.ajax.request(action,param,function(result){
					$gridContainer.unmask();
					if(result.success){
						if(sender.is(".add")){
							utilities.errorDialog(clientResource.msgWaitForConfirm);
						} else if(sender.is(".del")){
							friendGrid.refresh();
						}
					}
				},function () {
					$gridContainer.unmask();
				});
			});

			// var dataList = [
			// 	{'ranking': 0, 'user_id': 837, 'sleeptime': 0, 'type': 1, 'jumps': 0, 'miles': 0, 'rankchange': 0, 'photo': '', 'relation': 1, 'calorie': 0, 'user_name': 'test123'},
			// 	{'ranking': 0, 'user_id': 837, 'sleeptime': 0, 'type': 1, 'jumps': 0, 'miles': 0, 'rankchange': 1, 'photo': '', 'relation': 1, 'calorie': 0, 'user_name': 'test123'},
			// 	{'ranking': 0, 'user_id': 837, 'sleeptime': 0, 'type': 1, 'jumps': 0, 'miles': 0, 'rankchange': -1, 'photo': '', 'relation': 2, 'calorie': 0, 'user_name': 'test123'},
			// 	{'ranking': 0, 'user_id': 837, 'sleeptime': 0, 'type': 1, 'jumps': 0, 'miles': 0, 'rankchange': 0, 'photo': '', 'relation': 2, 'calorie': 0, 'user_name': 'test123'},
			// 	{'ranking': 0, 'user_id': 837, 'sleeptime': 0, 'type': 1, 'jumps': 0, 'miles': 0, 'rankchange': 0, 'photo': '', 'relation': 2, 'calorie': 0, 'user_name': 'test123'},
			// 	{'ranking': 0, 'user_id': 837, 'sleeptime': 0, 'type': 1, 'jumps': 0, 'miles': 0, 'rankchange': 1, 'photo': '', 'relation': 2, 'calorie': 0, 'user_name': 'test123'},
			// 	{'ranking': 0, 'user_id': 837, 'sleeptime': 0, 'type': 1, 'jumps': 0, 'miles': 0, 'rankchange': -1, 'photo': '', 'relation': 2, 'calorie': 0, 'user_name': 'test123'},

			// ];
			// grid.showData(dataList);

			function rankingFormatter(column, value, obj){
				var rankingEnum = nsbase.enums.rankingEnum.getEnumByValue(value);
				var cssName = rankingEnum.key;
				return '<span class="grid_icon '+ cssName +'"></span>';
			}

			function photoFormatter (column,value,obj) {
				var imgSrc = "../static/images/photo.png";
				if(value){
					imgSrc = value;
				}
				return '<img src="'+ imgSrc +'" width="30" height="30" onError="this.src=\'../static/images/photo.png\';"/>';
			}
			
			function colorieFormatter (column,value,obj) {
				return '<span class="grid_icon calorie"></span>' + value + ' cal';
			}
			function manageFormater (column,value,obj) {
				if(obj.user_id == userId){
					return "";
				}
				var relationEnum = nsbase.enums.relationshipEnum.getEnumByValue(value);
				if(relationEnum == nsbase.enums.relationshipEnum.friend){
					return '<a href="###"><span class="grid_icon del"></span></a>';
				}
				return '<a href="###"><span class="grid_icon add"></span></a>';
			}
		}
	}
})();